"use client"

import { useState, useEffect } from 'react'
import { motion } from "framer-motion"
import { Edit, Trophy, Users, Calendar, Star, Award, Target, TrendingUp, MapPin, Mail, Globe, Github, Linkedin } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Progress } from "@/components/ui/progress"
import { useAuth } from '@/contexts/auth-context'
import { usersApi } from '@/lib/api'
import Link from "next/link"

interface UserStats {
  competitions_participated: number
  projects_created: number
  teams_joined: number
  reputation_score: number
  profile_completion: number
}

const mockUser = {
  name: "Alex Chen",
  avatar: "/default-avatar.svg",
  title: "Full Stack Developer",
  school: "清华大学",
  level: "Kaggle Expert",
  joinDate: "2023-03-15",
  stats: {
    competitions: 24,
    wins: 8,
    teams: 15,
    points: 2847,
  },
}

const mockBadges = [
  { id: 1, name: "首次参赛", icon: "🎯", description: "完成第一次竞赛", earned: true },
  { id: 2, name: "团队合作", icon: "🤝", description: "成功组队10次", earned: true },
  { id: 3, name: "连胜达人", icon: "🔥", description: "连续获奖3次", earned: true },
  { id: 4, name: "AI专家", icon: "🤖", description: "在AI竞赛中获奖", earned: true },
  { id: 5, name: "数据科学家", icon: "📊", description: "完成5个数据科学项目", earned: false },
  { id: 6, name: "开源贡献者", icon: "💻", description: "为开源项目贡献代码", earned: false },
  { id: 7, name: "导师", icon: "👨‍🏫", description: "指导新手参赛", earned: false },
  { id: 8, name: "全能选手", icon: "⭐", description: "在多个领域获奖", earned: false },
]

const mockAchievements = [
  {
    id: 1,
    competition: "Kaggle - House Prices Competition",
    rank: "3rd Place",
    date: "2024-01-15",
    prize: "$3,000",
    platform: "Kaggle",
    teammates: ["Sarah Kim", "Mike Johnson"],
  },
  {
    id: 2,
    competition: "天池 - 智慧城市AI挑战赛",
    rank: "1st Place",
    date: "2023-12-20",
    prize: "¥50,000",
    platform: "天池",
    teammates: ["Lisa Wang", "Tom Zhang", "Emma Liu"],
  },
  {
    id: 3,
    competition: "Devpost - Climate Change Hackathon",
    rank: "2nd Place",
    date: "2023-11-10",
    prize: "$10,000",
    platform: "Devpost",
    teammates: ["David Chen"],
  },
]

const mockRegistered = [
  {
    id: 1,
    title: "Google AI Challenge 2024",
    platform: "Google",
    deadline: "2024-02-25",
    status: "active",
  },
  {
    id: 2,
    title: "Microsoft Azure Hackathon",
    platform: "Microsoft",
    deadline: "2024-02-22",
    status: "active",
  },
  {
    id: 3,
    title: "OpenAI GPT-4 创新大赛",
    platform: "OpenAI",
    deadline: "2024-02-28",
    status: "pending",
  },
]

export default function ProfilePage() {
  const { user, isLoading } = useAuth()
  const [stats, setStats] = useState<UserStats | null>(null)

  useEffect(() => {
    if (user) {
      fetchUserStats()
    }
  }, [user])

  const fetchUserStats = async () => {
    try {
      const response = await usersApi.getCurrentUserStats()
      setStats(response.data)
    } catch (error) {
      console.error('Failed to fetch user stats:', error)
      // 使用模拟数据作为后备
      setStats({
        competitions_participated: 24,
        projects_created: 8,
        teams_joined: 15,
        reputation_score: user?.reputation_score || 2847,
        profile_completion: 75
      })
    }
  }

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center pt-20">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-white"></div>
      </div>
    )
  }

  if (!user) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center pt-20">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-white"></div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 pt-20">
      <div className="container mx-auto px-4 py-8">
        {/* 个人信息卡片 */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} className="mb-8">
          <Card className="glass border-white/20">
            <CardContent className="p-8">
              <div className="flex flex-col md:flex-row items-center gap-6">
                <Avatar className="w-32 h-32">
                  <AvatarImage src={user.avatar_url || "/default-avatar.svg"} />
                  <AvatarFallback className="text-2xl bg-gradient-to-r from-blue-500 to-purple-500 text-white">
                    {user.username.charAt(0).toUpperCase()}
                  </AvatarFallback>
                </Avatar>

                <div className="flex-1 text-center md:text-left">
                  <h1 className="text-3xl font-bold mb-2 text-white">{user.full_name || user.username}</h1>
                  <p className="text-xl text-gray-300 mb-2">@{user.username}</p>
                  {user.bio && <p className="text-gray-400 mb-4">{user.bio}</p>}

                  <div className="flex flex-wrap justify-center md:justify-start gap-2 mb-4">
                    <Badge className="bg-blue-500/20 text-blue-400">声誉: {user.reputation_score}</Badge>
                    <Badge variant="outline" className="border-white/20 text-white">
                      加入于 {new Date(user.created_at).toLocaleDateString()}
                    </Badge>
                  </div>

                  {/* 联系信息 */}
                  <div className="flex flex-wrap justify-center md:justify-start gap-4 mb-4 text-white/80">
                    <div className="flex items-center gap-2">
                      <Mail className="w-4 h-4" />
                      <span className="text-sm">{user.email}</span>
                    </div>
                    {user.location && (
                      <div className="flex items-center gap-2">
                        <MapPin className="w-4 h-4" />
                        <span className="text-sm">{user.location}</span>
                      </div>
                    )}
                  </div>

                  {/* 社交链接 */}
                  <div className="flex justify-center md:justify-start gap-4 mb-6">
                    {user.website && (
                      <a href={user.website} target="_blank" rel="noopener noreferrer" className="text-blue-400 hover:text-blue-300">
                        <Globe className="w-5 h-5" />
                      </a>
                    )}
                    {user.github_url && (
                      <a href={user.github_url} target="_blank" rel="noopener noreferrer" className="text-white hover:text-gray-300">
                        <Github className="w-5 h-5" />
                      </a>
                    )}
                    {user.linkedin_url && (
                      <a href={user.linkedin_url} target="_blank" rel="noopener noreferrer" className="text-blue-500 hover:text-blue-400">
                        <Linkedin className="w-5 h-5" />
                      </a>
                    )}
                  </div>

                  {stats && (
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                      <div className="text-center">
                        <div className="text-2xl font-bold text-blue-400">{stats.competitions_participated}</div>
                        <div className="text-sm text-gray-400">参赛次数</div>
                      </div>
                      <div className="text-center">
                        <div className="text-2xl font-bold text-green-400">{stats.projects_created}</div>
                        <div className="text-sm text-gray-400">创建项目</div>
                      </div>
                      <div className="text-center">
                        <div className="text-2xl font-bold text-purple-400">{stats.teams_joined}</div>
                        <div className="text-sm text-gray-400">加入团队</div>
                      </div>
                      <div className="text-center">
                        <div className="text-2xl font-bold text-yellow-400">{stats.reputation_score}</div>
                        <div className="text-sm text-gray-400">声誉分</div>
                      </div>
                    </div>
                  )}

                  {/* 资料完成度 */}
                  {stats && (
                    <div className="bg-white/5 rounded-lg p-4">
                      <div className="flex items-center justify-between mb-2">
                        <span className="text-white/80">资料完成度</span>
                        <span className="text-white font-medium">{stats.profile_completion}%</span>
                      </div>
                      <Progress value={stats.profile_completion} className="h-2" />
                    </div>
                  )}
                </div>

                <div className="flex flex-col gap-2">
                  <Link href="/profile/edit">
                    <Button className="gap-2 bg-gradient-to-r from-blue-600 to-purple-600">
                      <Edit className="w-4 h-4" />
                      编辑资料
                    </Button>
                  </Link>
                  <Button variant="outline" className="gap-2 bg-transparent border-white/20 text-white">
                    <Star className="w-4 h-4" />
                    分享资料
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        </motion.div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* 左侧内容 */}
          <div className="lg:col-span-2 space-y-8">
            {/* 成就徽章 */}
            <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.2 }}>
              <Card className="glass border-0">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Award className="w-5 h-5 text-yellow-400" />
                    成就徽章
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                    {mockBadges.map((badge) => (
                      <motion.div
                        key={badge.id}
                        whileHover={{ scale: 1.05 }}
                        className={`p-4 rounded-lg text-center cursor-pointer transition-all ${
                          badge.earned
                            ? "bg-gradient-to-br from-yellow-500/20 to-orange-500/20 border border-yellow-500/30"
                            : "bg-gray-800/50 border border-gray-700 opacity-50"
                        }`}
                        title={badge.description}
                      >
                        <div className="text-3xl mb-2">{badge.icon}</div>
                        <div className="text-sm font-medium">{badge.name}</div>
                      </motion.div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </motion.div>

            {/* 战绩时间轴 */}
            <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.4 }}>
              <Card className="glass border-0">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Trophy className="w-5 h-5 text-purple-400" />
                    战绩时间轴
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-6">
                    {mockAchievements.map((achievement, index) => (
                      <motion.div
                        key={achievement.id}
                        initial={{ opacity: 0, x: -20 }}
                        animate={{ opacity: 1, x: 0 }}
                        transition={{ delay: 0.6 + index * 0.1 }}
                        className="flex gap-4"
                      >
                        <div className="flex flex-col items-center">
                          <div
                            className={`w-3 h-3 rounded-full ${
                              achievement.rank === "1st Place"
                                ? "bg-yellow-400"
                                : achievement.rank === "2nd Place"
                                  ? "bg-gray-300"
                                  : "bg-orange-400"
                            }`}
                          />
                          {index < mockAchievements.length - 1 && <div className="w-px h-16 bg-gray-600 mt-2" />}
                        </div>

                        <div className="flex-1 pb-6">
                          <div className="flex items-center justify-between mb-2">
                            <h4 className="font-semibold">{achievement.competition}</h4>
                            <Badge
                              className={
                                achievement.rank === "1st Place"
                                  ? "bg-yellow-500/20 text-yellow-400"
                                  : achievement.rank === "2nd Place"
                                    ? "bg-gray-500/20 text-gray-300"
                                    : "bg-orange-500/20 text-orange-400"
                              }
                            >
                              {achievement.rank}
                            </Badge>
                          </div>

                          <div className="flex items-center gap-4 text-sm text-gray-400 mb-2">
                            <span>{achievement.platform}</span>
                            <span>{achievement.date}</span>
                            <span className="text-green-400 font-medium">{achievement.prize}</span>
                          </div>

                          <div className="flex items-center gap-2">
                            <Users className="w-4 h-4 text-gray-400" />
                            <span className="text-sm text-gray-400">队友: {achievement.teammates.join(", ")}</span>
                          </div>
                        </div>
                      </motion.div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          </div>

          {/* 右侧边栏 */}
          <div className="space-y-6">
            {/* 技能雷达 */}
            <motion.div initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.6 }}>
              <Card className="glass border-0">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Target className="w-5 h-5 text-blue-400" />
                    技能等级
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  {[
                    { skill: "Machine Learning", level: 85 },
                    { skill: "Python", level: 92 },
                    { skill: "Data Analysis", level: 78 },
                    { skill: "Deep Learning", level: 70 },
                    { skill: "Web Development", level: 88 },
                  ].map((item) => (
                    <div key={item.skill}>
                      <div className="flex justify-between text-sm mb-1">
                        <span>{item.skill}</span>
                        <span>{item.level}%</span>
                      </div>
                      <Progress value={item.level} className="h-2" />
                    </div>
                  ))}
                </CardContent>
              </Card>
            </motion.div>

            {/* 已报名竞赛 */}
            <motion.div initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 0.8 }}>
              <Card className="glass border-0">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Calendar className="w-5 h-5 text-green-400" />
                    已报名竞赛
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  {mockRegistered.map((comp) => (
                    <div key={comp.id} className="p-3 rounded-lg bg-white/5">
                      <h4 className="font-medium text-sm mb-1">{comp.title}</h4>
                      <div className="flex items-center justify-between text-xs">
                        <span className="text-gray-400">{comp.platform}</span>
                        <Badge variant={comp.status === "active" ? "default" : "outline"}>
                          {comp.status === "active" ? "进行中" : "待开始"}
                        </Badge>
                      </div>
                      <div className="text-xs text-gray-400 mt-1">截止: {comp.deadline}</div>
                    </div>
                  ))}
                </CardContent>
              </Card>
            </motion.div>

            {/* 成长趋势 */}
            <motion.div initial={{ opacity: 0, x: 20 }} animate={{ opacity: 1, x: 0 }} transition={{ delay: 1 }}>
              <Card className="glass border-0">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <TrendingUp className="w-5 h-5 text-purple-400" />
                    成长趋势
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="text-center">
                    <div className="text-3xl font-bold text-green-400 mb-2">+15%</div>
                    <div className="text-sm text-gray-400 mb-4">本月积分增长</div>
                    <div className="space-y-2 text-sm">
                      <div className="flex justify-between">
                        <span className="text-gray-400">排名</span>
                        <span className="text-blue-400">#247 ↑12</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-gray-400">获奖率</span>
                        <span className="text-green-400">33.3%</span>
                      </div>
                      <div className="flex justify-between">
                        <span className="text-gray-400">团队评分</span>
                        <span className="text-yellow-400">4.8/5.0</span>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          </div>
        </div>
      </div>
    </div>
  )
}
